package routes

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"net/http"
)

func registerMQTTRoutes() {
	http.HandleFunc("/api/getLedON", handlegetLedON)
	http.HandleFunc("/api/getLedOFF", handlegetLedOFF)
}

func handlegetLedON(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		w.Write([]byte("getLedON+++++++++"))
		var broker = "127.0.0.1"
		var port = 1883
		opts := mqtt.NewClientOptions()
		opts.AddBroker(fmt.Sprintf("mqtt://%s:%d", broker, port))
		opts.SetClientID("go_mqtt_client")
		opts.SetUsername("ziu")
		opts.SetPassword("zxcvbnm,./123")
		//opts.SetDefaultPublishHandler(messagePubHandler)
		opts.OnConnect = connectHandler
		opts.OnConnectionLost = connectLostHandler
		client := mqtt.NewClient(opts)
		if token := client.Connect(); token.Wait() && token.Error() != nil {
			panic(token.Error())
		}
		text := fmt.Sprintf("")
		token := client.Publish("xiaomi/home1/control/led/on", 0, false, text)
		token.Wait()
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}

func handlegetLedOFF(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		w.Write([]byte("getLedOFF--------"))
		var broker = "127.0.0.1"
		var port = 1883
		opts := mqtt.NewClientOptions()
		opts.AddBroker(fmt.Sprintf("mqtt://%s:%d", broker, port))
		opts.SetClientID("go_mqtt_client")
		opts.SetUsername("ziu")
		opts.SetPassword("zxcvbnm,./123")
		//opts.SetDefaultPublishHandler(messagePubHandler)
		opts.OnConnect = connectHandler
		opts.OnConnectionLost = connectLostHandler
		client := mqtt.NewClient(opts)
		if token := client.Connect(); token.Wait() && token.Error() != nil {
			panic(token.Error())
		}
		text := fmt.Sprintf("")
		token := client.Publish("xiaomi/home1/control/led/off", 0, false, text)
		token.Wait()
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	fmt.Println("Connected")
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	fmt.Printf("Connect lost: %v", err)
}
